<template>
  <div class="todo-item">
    <!-- v-model改为 :checked ？-->
    <input
      type="checkbox"
      v-model="todo.completed"
      @change="$emit('toggle', todo.id)"
    />
    <label
      v-if="!editing"
      @click="!todo.completed ? (editing = true) : 1"
      :class="todo.completed ? 'completed' : ''"
      >{{ todo.content }}
    </label>
    <input
      v-else
      v-todo-focus
      :value="todo.content"
      @keyup.esc="editing = false"
      @keyup.enter="handleEdit"
      @blur="handleEdit"
      type="text"
    />
    <button @click="$emit('delete', todo.id)"></button>
  </div>
</template>

<script>
export default {
  name: 'TodoItem',
  // 自定义指令
  directives: {
    'todo-focus': {
      inserted: function (el) {
        el.focus()
        // el.select() 全选
      },
    },
  },
  props: {
    todo: {
      type: Object,
      required: true,
    },
  },
  data() {
    return { editing: false }
  },
  methods: {
    handleEdit(e) {
      // 1. 获取新输入的value
      // 2. 向父组件传id，value
      // 3. 修改编辑状态为true，变为label
      // trim
      if (this.editing == true) {
        //失焦和回车 放一起会执行两次事件，通过判断避免
        this.$emit('edit', this.todo.id, e.target.value)
        this.editing = false
      }
    },
  },
}
</script>

<style lang="stylus">
@import '~styles/theme.styl';
// @import '@/assets/styles/theme.styl'; //等同上一句，@代指src的路径
@import '~styles/mixins.styl'

.todo-item
  display: flex;
  justify-content: space-between;
  margin: 3px 7px 0 0;
  padding: 8px 10px;
  border-bottom: 1px solid rgba(158, 176, 181,0.3);
  color: #666;
  font-size: 24px;
  transition: all 0.5s;
  border-radius: 10px;
  &:hover
    box-shadow: 4px 2px 5px $blue;
    button
      opacity 1;
    button::after
      content: url('~images/delete.svg');
  input[type="checkbox"]
  //表单元素美化原则：去掉浏览器自带样式，使用自定义样式
    width: 40px;
    height: 40px;
    clearDefault();
    // &表示父元素
    &::after
      content: url('~images/unChecked.svg');

    &:checked::after
      content: url('~images/Checked.svg');
  input[type='text']
    flex: 1;
    margin-left: 5px;
    padding-left : 5px;
    clearDefault();
    background-color: rgba(247, 245, 244, 0.2);
    font-size: 24px;
    color: $cat;
    box-shadow: 0px 0px 2px 2px rgba(105, 195, 243,1);
    border-radius: 10px;
  label
    flex: 1;
    margin-left: 10px;
    line-height: 40px;
    transition: all 0.4s;
    &.completed
        text-decoration: line-through white;
        color: $blue2;
  button
    width: 40px;
    heigtht: 40px;
    clearDefault();
    background-color: transparent;
    cursor: pointer;
    transition: all 0.5s;
    &::after
      content: url('~images/delete.svg');
</style>
